#include "orgmgmt.h"
#include "ui_orgmgmt.h"
#include <QDebug>

#include "DataBase/database.h"
#include "mainwindow.h"
#include <QMessageBox>
#include <QStandardItem>

static QTreeWidgetItem * item;

OrgMgmt::OrgMgmt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OrgMgmt)
{
    ui->setupUi(this);

    //初始化组织树
    on_btn_refresh_clicked();
    Root_Index = ui->cmb_parent->rootModelIndex();
}

OrgMgmt::~OrgMgmt()
{
    delete ui;
}

QTreeWidgetItem* OrgMgmt::AddTreeNode(QTreeWidgetItem *parent,QString name,QTreeWidget* root)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(QStringList()<<name);
    if(parent == nullptr) root->addTopLevelItem(item);
    else parent->addChild(item);
    if(root == ui->treeWidget) item->setCheckState(0, Qt::Unchecked);
    return item;
}

//树搜索
void OrgMgmt::InitTree(QTreeWidgetItem *parent, int id, QTreeWidget* root)
{
    QList<QString> list = map_name_parent.keys(id); //list存机构名字
    for(int i=0; i<list.size(); i++){
        item = AddTreeNode(parent, list[i], root);
        InitTree(item, map_name_id.value(list[i]), root); //遍历子节点
    }
}

void OrgMgmt::on_btn_add_clicked()
{
    ui->lb_choose->setText("当前选择:\t添加机构");
    ui->btn_save->setText("添加");

    ui->le_name->clear();
    ui->le_code->clear();
    ui->le_pos->clear();
    ui->ed_remark->clear();
    ui->cmb_parent->setCurrentIndex(-1);

    item_id = -1;
}

void OrgMgmt::on_btn_cancel_clicked()
{
    on_btn_add_clicked();
}

void OrgMgmt::on_btn_save_clicked()
{
    QString sql;
    QSqlQuery query;
    QString name = ui->le_name->text();
    QString code = ui->le_code->text();
    QString pos = ui->le_pos->text();
    QString remark = ui->ed_remark->toPlainText();
    QString parent = ui->cmb_parent->currentText();
    int parent_id = map_name_id.contains(parent) ? map_name_id.value(parent) : 0;
    QString route = "";

    if(parent_id == item_id){
        QMessageBox::information(this, "提示", "父级机构设置错误");
        return;
    }
    if(name.isEmpty() || code.isEmpty()){
        QMessageBox::information(this, "提示", "名称和编号不得为空");
        return;
    }

    query = mydb->query("dm_organization","route",QString(" WHERE id=%1").arg(parent_id));
    if(query.next()){
        route = query.value(0).toString();
        if(route.isEmpty()) route = QString("%1").arg(parent_id);
        else route += QString(",%1").arg(parent_id);
    }

    if(item_id <= 0){
        sql = QString("INSERT INTO dm_organization (org_no,org_full_name,parent_id,sort,remark,create_time,route) \
VALUES ('%1','%2','%3','%4','%5', NOW(), '%6');").arg(code).arg(name).arg(parent_id).arg(pos).arg(remark).arg(route);
        if(query.exec(sql)){
            mydb->addLog(DM_Window->current_user_id, "机构管理", QString("新增机构\\'%1\\'").arg(name), "1");
            query = mydb->query("dm_organization","id"," WHERE id=last_insert_id()");
            if(query.next()) item_id = query.value(0).toInt();
            map_name_id.insert(name, item_id);
            map_name_parent.insert(name, parent_id);
        }
    }else{
        sql = QString("UPDATE dm_organization SET org_no='%1',org_full_name='%2',parent_id='%3',sort='%4',\
remark='%5',update_time=NOW(),route='%6' WHERE id='%7'").arg(code).arg(name).arg(parent_id).arg(pos).arg(remark).arg(route).arg(item_id);
        if(query.exec(sql)){
            if(map_name_id.key(item_id) != name)
                mydb->addLog(DM_Window->current_user_id, "机构管理", QString("更改机构\\'%1\\'为\\'%2\\'").arg(map_name_id.key(item_id),name), "1");
            else
                mydb->addLog(DM_Window->current_user_id, "机构管理", QString("更改机构\\'%1\\'").arg(name), "1");
            map_name_id.remove(map_name_id.key(item_id));
            map_name_id.insert(name, item_id);
            map_name_parent.insert(name, parent_id);
        }
    }

    qDebug() << sql;
    on_btn_add_clicked();
    on_btn_refresh_clicked();
}


void OrgMgmt::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
    Q_UNUSED(column);
    ui->lb_choose->setText("当前选择:\t"+item->text(0));
    ui->btn_save->setText("更改");

    int row;
    QStringList route;
    QModelIndex index;

    QSqlQuery query = mydb->query("dm_organization", "*", QString(" WHERE id=%1").arg(map_name_id.value(item->text(0))));
    if(query.next()){
        item_id = map_name_id.value(item->text(0));
        ui->le_name->setText(query.value(2).toString());
        ui->le_code->setText(query.value(1).toString());
        ui->le_pos->setText(query.value(6).toString());
        ui->ed_remark->setText(query.value(7).toString());

        //combobox tree 定位
        index = Root_Index;
        ui->cmb_parent->setRootModelIndex(Root_Index);
        route = query.value(10).toString().split(",");
        for(int i=0; i<route.size(); i++){
            row = ui->cmb_parent->findText(map_name_id.key(route[i].toInt()));
//            qDebug() << "id" << route[i].toInt() << row;
            if(i == route.size()-1){
                ui->cmb_parent->setCurrentIndex(row);
            }else{
                index = ui->cmb_parent->model()->index(row, 0, index);
                ui->cmb_parent->setRootModelIndex(index);
            }
        }
        ui->cmb_parent->setRootModelIndex(Root_Index);
    }
}

void OrgMgmt::on_btn_refresh_clicked()
{
    map_name_id.clear();
    map_name_parent.clear();
    //获取机构
    QSqlQuery query=mydb->query("dm_organization", "id,org_full_name,parent_id", " WHERE delete_flag=0", " ORDER BY sort");
    while(query.next()){
        map_name_id.insert(query.value(1).toString(), query.value(0).toInt());
        map_name_parent.insert(query.value(1).toString(), query.value(2).toInt());
    }

    ui->treeWidget->clear();
    InitTree(nullptr, 0, ui->treeWidget);
    ui->treeWidget->expandAll();

    //父节点下拉选择框
    comboboxTree = new QTreeWidget();
    comboboxTree->addTopLevelItem(new QTreeWidgetItem(QStringList()<<"---"));
    InitTree(nullptr, 0, comboboxTree);
    QTreeView *treeView = new QTreeView(this);
    ui->cmb_parent->setModel(comboboxTree->model());
    treeView->setModel(comboboxTree->model());
    treeView->setHeaderHidden(true);
    treeView->expandAll();
    ui->cmb_parent->setView(treeView);
    ui->cmb_parent->setCurrentIndex(-1);
}


void OrgMgmt::on_btn_del_clicked()
{
    QString sql;
    QSqlQuery query;

    QList<int> list;
    QTreeWidgetItemIterator it(ui->treeWidget);
    while (*it) {
        if((*it)->checkState(0)){
            list.append(map_name_id.value((*it)->text(0)));
        }
        ++it;
    }

    if(list.size() <= 0){
        QMessageBox::information(this, "提示", "没有选择机构");
        return;
    }
    if(QMessageBox::No == QMessageBox::question(this, "提示",
        QString("确定要删除%1个机构吗？").arg(list.size()), QMessageBox::Yes|QMessageBox::No)) return;

    QString log = QString("删除%1个机构:").arg(list.size());
    for(int i=0; i<list.size(); i++){
        sql = QString("UPDATE dm_organization SET delete_flag=1 WHERE id='%1'").arg(list[i]);
        log += QString("<%1>").arg(map_name_id.key(list[i]));
        query.exec(sql);
//        qDebug() << sql;
    }
    mydb->addLog(DM_Window->current_user_id, "机构管理", log, "1");

    //刷新
    on_btn_add_clicked();
    on_btn_refresh_clicked();
}

